/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkClass } from 'arkanalyzer';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { Rule, Defects, MatcherTypes, MatcherCallback, ClassMatcher } from '../../Index';
import { IssueReport } from '../../model/Defects';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ArrayDefinitionCheck');
const gMetaData: BaseMetaData = {
    severity: 3,
    ruleDocPath: 'docs/avoid-overusing-custom-component-check.md',
    description: 'Preferentially use the @Builder method instead of custom components.',
};
const lifeCycleMethod: string[] = ['aboutToAppear', 'onDidBuild', 'aboutToDisappear', 'onPageShow', 'onPageHide', 'onBackPress'];
const TwoWaySyncDecoratorList: Set<string> = new Set(['Provide', 'Consume', 'Link', 'ObjectLink', 'LocalStorageLink', 'StorageLink']);
const IgnoreStructDecoratorList: Set<string> = new Set<string>(['Reusable', 'Entry']);

export class AvoidOverusingCustomComponentCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private buildMatcher: ClassMatcher = {
        matcherType: MatcherTypes.CLASS,
        hasViewTree: true
    };

    public registerMatchers(): MatcherCallback[] {
        const matchBuildCb: MatcherCallback = {
            matcher: this.buildMatcher,
            callback: this.check,
        };
        return [matchBuildCb];
    }

    public check = (arkClass: ArkClass): void => {
        if (arkClass.getDecorators().some(decorator =>
            IgnoreStructDecoratorList.has(decorator.getKind()))) {
            return;
        }
        if (!this.stateVarCheck(arkClass) && !this.isHasLifeCycleMethod(arkClass)) {
            this.reportIssue(arkClass);
        }
    };

    private stateVarCheck(arkClass: ArkClass): boolean {
        return arkClass.getFields().some(field =>
            field.getDecorators().some(decorator =>
                TwoWaySyncDecoratorList.has(decorator.getKind())
            )
        );
    }

    private isHasLifeCycleMethod(arkClass: ArkClass): boolean {
        let arkMethods = arkClass.getMethods();
        for (let method of arkMethods) {
            let methodName = method.getName();
            if (lifeCycleMethod.includes(methodName)) {
                return true;
            }
        }
        return false;
    }

    private reportIssue(arkClass: ArkClass): void {
        let code = arkClass.getCode();
        if (!code || code.length === 0) {
            return;
        }
        let baseLastLine = arkClass.getLine();
        let className = arkClass.getName();
        const filePath = arkClass.getDeclaringArkFile().getFilePath();
        let originalTexts = code.split('\n');
        let lineCount = -1;
        let startColumn = -1;
        for (let originalText of originalTexts) {
            lineCount++;
            if (!originalText.includes(className)) {
                continue;
            }
            startColumn = originalText.indexOf(className) + 1;
            break;
        }
        let endColumn = startColumn + className.length - 1;
        if (startColumn === -1) {
            return;
        }
        let lineNum = baseLastLine + lineCount;
        const severity = this.rule.alert ?? this.metaData.severity;
        let defects = new Defects(lineNum, startColumn, endColumn, this.metaData.description, severity,
            this.rule.ruleId, filePath, this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defects, undefined));
    }
}